// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <gtest/gtest.h>
#include <pollux/common/file/file_systems.h>
#include <pollux/testing/exec/writer_fuzzer.h>
#include <pollux/common/file/temp_directory_path.h>

using namespace kumo::pollux;
using namespace kumo::pollux::exec::test;

TEST(WriterFuzzerUtilTest, listFolders) {
  kumo::pollux::filesystems::registerLocalFileSystem();
  const auto tempFolder = exec::test::TempDirectoryPath::create();
  // Directory layout:
  // First layer:   dir1/   dir2/      dir3/    a
  // Second layer:  b       dir2_1/
  const auto dir1 = fmt::format("{}/dir1", tempFolder->getPath());
  const auto dir2 = fmt::format("{}/dir2", tempFolder->getPath());
  const auto dir2_1 = fmt::format("{}/dir2/dir2_1", tempFolder->getPath());
  const auto dir3 = fmt::format("{}/dir3", tempFolder->getPath());
  const auto a = fmt::format("{}/a", tempFolder->getPath());
  const auto b = fmt::format("{}/dir1/b", tempFolder->getPath());

  auto localFs = filesystems::getFileSystem(a, nullptr);
  {
    localFs->mkdir(dir1);
    localFs->mkdir(dir2);
    localFs->mkdir(dir2_1);
    localFs->mkdir(dir3);
    auto writeFile = localFs->openFileForWrite(a);
    writeFile = localFs->openFileForWrite(b);
  }
  auto folder = listFolders(std::string_view(tempFolder->getPath()));
  std::sort(folder.begin(), folder.end());
  ASSERT_EQ(folder, std::vector<std::string>({dir1, dir2, dir2_1, dir3}));

  localFs->remove(b);
  localFs->remove(dir1);
  folder = listFolders(std::string_view(tempFolder->getPath()));
  std::sort(folder.begin(), folder.end());
  ASSERT_EQ(folder, std::vector<std::string>({dir2, dir2_1, dir3}));

  localFs->remove(dir2_1);
  localFs->remove(dir2);
  localFs->remove(dir3);
  ASSERT_TRUE(listFolders(std::string_view(tempFolder->getPath())).empty());
}
